package main

import (
	"context"
	pb "fgo/advance/other/discovery/go-grpc/api"
	"fgo/advance/other/discovery/go-grpc/balancer"
	"flag"
	"fmt"
	"github.com/g4zhuj/grpc-wrapper/config"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"net"
	"os"
	"os/signal"
	"syscall"
)

var (
	host          string
	port          int
	svcName       string
	etcdEndpoints string
)

func init() {
	flag.StringVar(&svcName, "service", "hello_service", "service name")
	flag.StringVar(&host, "host", "0.0.0.0", "listening Host")
	flag.IntVar(&port, "port", 50051, "listening port")
	flag.StringVar(&etcdEndpoints, "endpoints", "http://127.0.0.1:2379", "etcd endpoints")
}

func main() {
	flag.Parse()
	var serverAddr = fmt.Sprintf("%s:%d", host, port)

	// set zap logger
	logcfg := config.LoggerConfig{}
	grpclog.SetLoggerV2(logcfg.NewLogger())

	lis, err := net.Listen("tcp", serverAddr)
	if err != nil {
		grpclog.Fatalf("failed to listen: %s", err)
	}
	defer lis.Close()

	s := grpc.NewServer()
	defer s.GracefulStop()

	pb.RegisterHelloServiceServer(s, &hello{})

	go balancer.Register(etcdEndpoints, svcName, serverAddr, 5)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)
	go func() {
		s := <-ch
		balancer.UnRegister()
		grpclog.Infof("balancer unregister:%s,%s ", svcName, serverAddr)

		if i, ok := s.(syscall.Signal); ok {
			os.Exit(int(i))
		} else {
			os.Exit(0)
		}

	}()

	if err := s.Serve(lis); err != nil {
		grpclog.Fatalf("failed to serve: %s", err)
	}
}

type hello struct {
}

func (*hello) Echo(ctx context.Context, req *pb.Payload) (*pb.Payload, error) {
	serverAddr := fmt.Sprintf("%s:%d", host, port)

	req.Data = req.Data + ", from:" + serverAddr
	return req, nil
}
